<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useNoteStore } from '../stores/noteStore'

const route = useRoute()
const router = useRouter()
const noteStore = useNoteStore()

const title = ref('')
const content = ref('')

onMounted(() => {
  const noteId = Number(route.params.id)
  if (noteId) {
    const note = noteStore.notes.find((n) => n.id === noteId)
    if (note) {
      title.value = note.title
      content.value = note.content
    }
  }
})

const saveNote = () => {
  if (!title.value.trim() || !content.value.trim()) {
    alert('标题和内容不能为空！')
    return
  }

  const noteId = Number(route.params.id)
  const noteData = {
    title: title.value,
    content: content.value
  }

  if (noteId) {
    noteStore.updateNote(noteId, noteData)
  } else {
    noteStore.addNote(noteData)
  }

  router.push('/notes')
}
</script>

<template>
  <div class="note-edit">
    <div class="edit-card">
      <h2>{{ route.params.id ? '编辑笔记' : '新建笔记' }}</h2>

      <div class="form">
        <div class="form-group">
          <label>标题</label>
          <input v-model="title" type="text" placeholder="输入标题" autofocus />
        </div>

        <div class="form-group">
          <label>内容</label>
          <textarea
            v-model="content"
            placeholder="输入内容"
            rows="8"
          ></textarea>
        </div>

        <div class="actions">
          <button class="save" @click="saveNote"><i>💾</i> 保存</button>
          <button class="cancel" @click="router.push('/notes')">
            <i>❌</i> 取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.note-edit {
  max-width: 800px;
  margin: 0 auto;
  padding: 1rem;
}

.edit-card {
  background: white;
  padding: 2rem;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

h2 {
  color: var(--primary-color);
  margin-bottom: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
  font-weight: 500;
}

textarea {
  resize: vertical;
  min-height: 150px;
}

.actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.actions button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 12px;
}

.cancel {
  background-color: #95a5a6;
}

i {
  font-style: normal;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .note-edit {
    padding: 8px;
  }

  .edit-card {
    padding: 16px;
  }

  h2 {
    font-size: 20px;
    margin-bottom: 16px;
  }

  .form-group {
    margin-bottom: 12px;
  }

  textarea {
    min-height: 120px;
  }

  .actions {
    gap: 8px;
  }

  .actions button {
    padding: 8px;
    font-size: 14px;
  }
}
</style>
